<?php
/**
 * Created by PhpStorm.
 * User: JYuans
 * Date: 2019/11/27
 * Time: 10:53
 */
namespace Bstage\Controller;

use Common\Model\CommonModel;

class UserController extends BstageController {

    /**
     * 获取用户账号列表接口
     */
    public function userQuery(){
        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条
        //是否获取全部
        $is_all = $_REQUEST["is_all"]?$_REQUEST["is_all"]:0;
        //查询条件
        $where = array();
        //筛选部门
        if($_REQUEST["search_depart_id"]){
            $where['depart_id'] = $_REQUEST['search_depart_id'];
        }
        //筛选用户类型
        if(is_numeric($_REQUEST["search_user_type"])){
            $where['user_type'] = $_REQUEST["search_user_type"];
        }
        //筛选级别
        if($_REQUEST["search_rank"]){
            $where['rank'] = ['in',$_REQUEST['search_rank']];
        }
        //筛选员工编号
        if($_REQUEST["search_number"]){
            $where['number'] = $_REQUEST['search_number'];
        }
        //筛选注册时间
        if($_REQUEST["search_start_time"]){
            if($_REQUEST["search_end_time"]){
                $where['add_time'] = ['between',strtotime($_REQUEST["search_start_time"]).",".(strtotime($_REQUEST["search_end_time"])+86399)];
            }else{
                $where['add_time'] = ['gt',strtotime($_REQUEST["search_start_time"])];
            }
        }else{
            if($_REQUEST["end_time"]){
                $where['add_time'] = ['lt',(strtotime($_REQUEST["search_end_time"])+86399)];
            }
        }
        //筛选姓名
        if($_REQUEST["search_name"]){
            $where['name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }
        //筛选手机号
        if($_REQUEST["search_phone"]){
            $where['phone'] = ['like','%'.$_REQUEST['search_phone'].'%'];
        }
        //筛选邮箱
        if($_REQUEST["search_email"]){
            $where['email'] = ['like','%'.$_REQUEST['search_email'].'%'];
        }

        $field = "user_id,depart_id,username,number,name,phone,email,rank,station,station_type,user_type,use_start_time,use_end_time,t_user_pass,add_time";
        if($is_all){
            $list_data = M('User')
                ->where($where)
                ->field($field)
                ->order('add_time DESC')
                ->select();
        }else{
            $list_data = M('User')
                ->where($where)
                ->field($field)
                ->order('add_time DESC')
                ->page($now_page,$page_size)
                ->select();
        }

        if(!$list_data) {
            $this->returnJson(503,'没有更多数据');
        }

        $depart_name_array = array();
        if($list_data){
            $depart_id_array = array_column($list_data,'depart_id');

            $depart_name_array = M("Department")
                ->where(['depart_id'=>['in',$depart_id_array]])
                ->getField("depart_id,name");
        }
        foreach($list_data as $key=>$value){
            $list_data[$key]['depart_name'] = isset($depart_name_array[$value['depart_id']])?$depart_name_array[$value['depart_id']]:"";

            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            if($value['user_type'] == 1){
                //长期账号
                $list_data[$key]['use_time'] = "长期有效";
                $list_data[$key]['user_type'] = "一般账号";
            }else{
                //临时账号
                $list_data[$key]['use_time'] = changeDateTime($value['use_start_time'])."--".changeDateTime($value['use_end_time']);
                $list_data[$key]['user_type'] = "临时账号";
            }
            unset($list_data[$key]['use_start_time']);
            unset($list_data[$key]['use_end_time']);

            $list_data[$key]['add_time'] = changeDateTime($value['add_time']);
        }

        $count = M('User')
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取对应考核临时账号接口
     */
    public function getExamineTemporaryUserList(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");
        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条
        //是否获取全部
        $is_all = $_REQUEST["is_all"]?$_REQUEST["is_all"]:0;
        //查询条件
        $where = array();
        //筛选部门
        if($_REQUEST["search_depart_id"]){
            $where['depart_id'] = $_REQUEST['search_depart_id'];
        }
        //筛选考核
        $user_id_array = M("MidExamineDownRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->getField("examine_user_id",true);
        $where['user_id'] = ['in',$user_id_array];

        $field = "user_id,depart_id,username,number,name,phone,email,rank,station,station_type,user_type,use_start_time,use_end_time,add_time";
        if($is_all){
            $list_data = M('User')
                ->where($where)
                ->field($field)
                ->order('add_time DESC')
                ->select();
        }else{
            $list_data = M('User')
                ->where($where)
                ->field($field)
                ->order('add_time DESC')
                ->page($now_page,$page_size)
                ->select();
        }

        if(!$list_data) {
            $this->returnJson(503,'没有更多数据');
        }

        $depart_name_array = array();
        if($list_data){
            $depart_id_array = array_column($list_data,'depart_id');

            $depart_name_array = M("Department")
                ->where(['depart_id'=>['in',$depart_id_array]])
                ->getField("depart_id,name");
        }
        foreach($list_data as $key=>$value){
            $list_data[$key]['depart_name'] = isset($depart_name_array[$value['depart_id']])?$depart_name_array[$value['depart_id']]:"";

            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            if($value['user_type'] == 1){
                //长期账号
                $list_data[$key]['use_time'] = "长期有效";
                $list_data[$key]['user_type'] = "一般账号";
            }else{
                //临时账号
                $list_data[$key]['use_time'] = changeDateTime($value['use_start_time'])."--".changeDateTime($value['use_end_time']);
                $list_data[$key]['user_type'] = "临时账号";
            }
            unset($list_data[$key]['use_start_time']);
            unset($list_data[$key]['use_end_time']);

            $list_data[$key]['add_time'] = changeDateTime($value['add_time']);
        }

        $count = M('User')
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 添加账号方法
     */
    public function addUserAction(){
        $new_data = array();
        $new_data['depart_id'] = $_REQUEST["depart_id"]?$_REQUEST["depart_id"]:$this->errorReturn("请选择所属部门");
        $new_data['number'] = $_REQUEST["number"]?$_REQUEST["number"]:$this->errorReturn("请输入员工编号");
        $check_username = M("User")
            ->where(['number'=>$new_data['number']])
            ->count();
        if($check_username){
            $this->errorReturn("该员工编号已存在");
        }
        $new_data['username'] = $_REQUEST["username"]?$_REQUEST["username"]:$this->errorReturn("请输入登陆账号");
        $check_username = M("User")
            ->where(['username'=>$new_data['username']])
            ->count();
        if($check_username){
            $this->errorReturn("该用户名已存在");
        }
        $new_data['phone'] = $_REQUEST["phone"]?$_REQUEST["phone"]:"";
        if($new_data['phone']){
            $check_phone = M("User")
                ->where(['phone'=>$new_data['phone']])
                ->count();
            if($check_phone){
                $this->errorReturn("该手机号已存在");
            }
        }
        $new_data['email'] = $_REQUEST["email"]?$_REQUEST["email"]:"";
        if($new_data['email']) {
            $check_email = M("User")
                ->where(['email' => $new_data['email']])
                ->count();
            if ($check_email) {
                $this->errorReturn("该邮箱已存在");
            }
        }

        $new_data['password'] = $_REQUEST["password"]?md5($_REQUEST["password"]):$this->errorReturn("请输入密码");

        $new_data['name'] = $_REQUEST["name"]?$_REQUEST["name"]:$this->errorReturn("请输入姓名");
        $new_data['rank'] = $_REQUEST["rank"]?$_REQUEST["rank"]:$this->errorReturn("请选择级别");
        if($new_data['rank'] > count(CommonModel::rank_str_array) || $new_data['rank'] <=0){
            $this->errorReturn("请输入正确的级别参数，可用参数为：1~".count(CommonModel::rank_str_array));
        }
        $new_data['station'] = $_REQUEST["station"]?$_REQUEST["station"]:$this->errorReturn("请输入职务");
        $new_data['station_type'] = $_REQUEST["station_type"]?$_REQUEST["station_type"]:"";
        $new_data['user_type'] = is_numeric($_REQUEST["user_type"])?$_REQUEST["user_type"]:$this->errorReturn("请选择账号类型");
        if($new_data['user_type'] == 0){
            $new_data['use_start_time'] = $_REQUEST["use_start_time"]?strtotime($_REQUEST["use_start_time"]):$this->errorReturn("请输入临时账号使用期限，开始时间");
            $new_data['use_end_time'] = $_REQUEST["use_end_time"]?strtotime($_REQUEST["use_end_time"])+86399:$this->errorReturn("请输入临时账号使用期限，结束时间");
            if($new_data['use_start_time'] >= $new_data['use_end_time']){
                $this->errorReturn("期限开始时间必须小于结束时间");
            }
        }else if($new_data['user_type'] == 1){
            $new_data['use_start_time'] = $_REQUEST["use_start_time"]?strtotime($_REQUEST["use_start_time"]):0;
            $new_data['use_end_time'] = $_REQUEST["use_end_time"]?strtotime($_REQUEST["use_end_time"])+86399:0;
        }else{
            $this->errorReturn("账号类型参数错误");
        }
        $new_data['add_time'] = time();

        $add_result = M("User")
            ->add($new_data);
        if(!$add_result){
            $this->errorReturn("添加账号失败，请重新尝试");
        }

        $this->successReturn("注册成功");
    }

    /**
     * 修改账号方法
     */
    public function editUserAction(){
        $user_id = $_REQUEST["user_id"]?$_REQUEST["user_id"]:$this->errorReturn("缺少用户账号ID");

        $new_data = array();
        $new_data['depart_id'] = $_REQUEST["depart_id"]?$_REQUEST["depart_id"]:$this->errorReturn("请选择所属部门");
        $new_data['number'] = $_REQUEST["number"]?$_REQUEST["number"]:$this->errorReturn("请输入员工编号");
        $check_username = M("User")
            ->where(['number'=>$new_data['number'],'user_id'=>['neq',$user_id]])
            ->count();
        if($check_username){
            $this->errorReturn("该员工编号已存在");
        }
        $new_data['username'] = $_REQUEST["username"]?$_REQUEST["username"]:$this->errorReturn("请输入登陆账号");
        $check_username = M("User")
            ->where(['username'=>$new_data['username'],'user_id'=>['neq',$user_id]])
            ->count();
        if($check_username){
            $this->errorReturn("该用户名已存在");
        }
        $new_data['phone'] = $_REQUEST["phone"]?$_REQUEST["phone"]:"";
        if($new_data['phone']) {
            $check_phone = M("User")
                ->where(['phone' => $new_data['phone'], 'user_id' => ['neq', $user_id]])
                ->count();
            if ($check_phone) {
                $this->errorReturn("该手机号已存在");
            }
        }
        $new_data['email'] = $_REQUEST["email"]?$_REQUEST["email"]:"";
        if($new_data['email']) {
            $check_email = M("User")
                ->where(['email' => $new_data['email'], 'user_id' => ['neq', $user_id]])
                ->count();
            if ($check_email) {
                $this->errorReturn("该邮箱已存在");
            }
        }

        $new_data['name'] = $_REQUEST["name"]?$_REQUEST["name"]:$this->errorReturn("请输入姓名");
        $new_data['rank'] = $_REQUEST["rank"]?$_REQUEST["rank"]:$this->errorReturn("请选择级别");
        if($new_data['rank'] > count(CommonModel::rank_str_array) || $new_data['rank'] <=0){
            $this->errorReturn("请输入正确的级别参数，可用参数为：1~".count(CommonModel::rank_str_array));
        }
        $new_data['station'] = $_REQUEST["station"]?$_REQUEST["station"]:$this->errorReturn("请输入职务");
        $new_data['station_type'] = $_REQUEST["station_type"]?$_REQUEST["station_type"]:"";
        $new_data['update_time'] = time();

        $edit_result = M("User")
            ->where(['user_id'=>$user_id])
            ->save($new_data);
        if(!$edit_result){
            $this->errorReturn("修改账号数据失败，请重新尝试");
        }

        $this->successReturn("修改成功");
    }

    /**
     * 删除账号方法
     */
    public function deleteUserAction(){
        $id_str = $_REQUEST["id_str"]?$_REQUEST["id_str"]:$this->errorReturn("请选择需要删除的账号");

        $delete_result = M("User")
            ->where(['user_id'=>['in',$id_str]])
            ->delete();

        if($delete_result){
            $this->successReturn("删除成功");
        }else{
            $this->errorReturn("删除失败，请重新尝试");
        }
    }

    /**
     * 获取账号数据方法
     */
    public function getUserDataAction(){
        $user_id = $_REQUEST["user_id"]?$_REQUEST["user_id"]:$this->errorReturn("缺少用户账号ID");

        $data = M("User")
            ->where(['user_id'=>$user_id])
            ->field("depart_id,number,username,name,phone,email,rank,station,station_type")
            ->find();
        if(!$data){
            $this->errorReturn("用户ID错误");
        }

        $this->successReturn("获取成功",$data);
    }

    /**
     * 重置密码接口
     */
    public function editPasswordAction(){
        $user_id = $_REQUEST["user_id"]?$_REQUEST["user_id"]:$this->errorReturn("缺少用户账号ID");

        $password = $_REQUEST["password"]?md5($_REQUEST["password"]):$this->errorReturn("请输入密码");

        $update_result = M("User")
            ->where(['user_id'=>$user_id])
            ->setField("password",$password);
        if($update_result){
            $this->successReturn("重置成功");
        }else{
            $this->errorReturn("新密码不能与原密码相同");
        }
    }

    /**
     * 批量添加临时账号接口
     */
    public function addTemporaryUser(){
        $user_count = is_numeric($_REQUEST["user_count"])?$_REQUEST["user_count"]:$this->errorReturn("请输入需要生成的账号数量，参数必须为数字");
        $depart_id = $_REQUEST["depart_id"]?$_REQUEST["depart_id"]:$this->errorReturn("请选择所属部门");

        $check_depart_id = M("Department")
            ->where(['depart_id'=>$depart_id])
            ->count();
        if(!$check_depart_id){
            $this->errorReturn("部门ID错误");
        }

        if($user_count <= 0){
            $this->errorReturn("生成账号数量必须大于0");
        }

        $new_data = array();
        $new_data['depart_id'] = $depart_id;
        $new_data['rank'] = 1;
        $new_data['user_type'] = 0;
        $new_data['add_time'] = time();
        $new_data['use_start_time'] = $_REQUEST["use_start_time"]?strtotime($_REQUEST["use_start_time"])+86399:$this->errorReturn("请输入临时账号使用期限，开始时间");
        $new_data['use_end_time'] = $_REQUEST["use_end_time"]?strtotime($_REQUEST["use_end_time"])+86399:$this->errorReturn("请输入临时账号使用期限，结束时间");
        if($new_data['use_start_time'] >= $new_data['use_end_time']){
            $this->errorReturn("期限结束时间必须大于开始时间");
        }
        if(time() >= $new_data['use_end_time']){
            $this->errorReturn("期限结束时间必须大于当前时间");
        }

        //获取临时账号前缀标识
        //$username_flag = $this->generateTemporaryUsername();
        /*if(!$username_flag){
            $this->errorReturn("获取临时账号标识失败，请重新尝试");
        }

        //获取临时账号后续字符串
        $str_len = strlen($user_count);
        $str_flag = "";
        for($i = 0;$i < $str_len;$i++){
            $str_flag = $str_flag."0";
        }*/

        $model = M();
        $model->startTrans();

        //循环生成账号数据
        for($i = 0;$i < $user_count;$i++){
            $current_i = $i + 1;
            /*$new_data['username'] = $username_flag.mb_substr($str_flag,0,$str_len - strlen($current_i)).$current_i;
            $new_data['password'] = md5($new_data['username']);*/
            do{
                $new_data['username'] = randnumkeys(8);
                $check_username = M("User")
                    ->where(['username'=>$new_data['username']])
                    ->count();
            }while($check_username);
            $new_data['t_user_pass'] = randnumkeys(8);
            $new_data['password'] = md5($new_data['t_user_pass']);
            $new_data['name'] = $new_data['username'];

            $add_user_result = M("User")
                ->add($new_data);
            if(!$add_user_result){
                $model->rollback();
                $this->errorReturn("添加账号失败，请重新尝试");
            }
        }

        $model->commit();
        $this->successReturn("临时账号生成成功");
    }

    /**
     * 中层考核发送通知邮件
     */
    public function midExamineSendEmailAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id'] ? $_REQUEST['mid_ex_id'] : $this->errorReturn("缺少中层考核ID");

        $mid_ex_data = M("MidExamine")
            ->where(["mid_ex_id"=>$mid_ex_id])
            ->field("status,title,same_start_time,same_end_time,up_start_time,up_end_time")
            ->find();
        if(!$mid_ex_data){
            $this->errorReturn("中层考核ID错误");
        }
        if($mid_ex_data['status'] == 1){
            $this->errorReturn("中层考核状态为：进行中，才能发通知邮件");
        }

        $same_relation_list = M("MidExamineSameRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->getField("examine_user_id",true);

        $up_relation_list = M("MidExamineUpRelation")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->getField("examine_user_id",true);

        $user_id_array = array();
        if($same_relation_list){
            if($up_relation_list){
                $user_id_array = array_merge($same_relation_list,$up_relation_list);
            }else{
                $user_id_array = $same_relation_list;
            }
        }else{
            if($up_relation_list){
                $user_id_array = $up_relation_list;
            }else{
                $this->errorReturn("该中层考核未设置考评关系，无法发送邮件");
            }
        }

        $user_data = M("User")
            ->where(['user_id'=>['in',$user_id_array]])
            ->field("name,email,rank")
            ->select();
        if(!$user_data){
            $this->errorReturn("该中层考核设置考评关系对应用户已被删除");
        }

        $email_array = array();

        $same_time = changeDate($mid_ex_data['same_start_time'])."至".changeDate($mid_ex_data['same_end_time']);
        $up_time = changeDate($mid_ex_data['up_start_time'])."至".changeDate($mid_ex_data['up_end_time']);
        foreach($user_data as $key=>$value){
            if(!$value['email']){
                continue;
            }
            $new_email_data = array();
            $new_email_data['email'] = $value['email'];
            $new_email_data['title'] = $mid_ex_data['title'];
            $new_email_data['name'] = $value['name'];
            if($value['rank'] == 5){
                $new_email_data['email_body'] =  "<p>内容：</p>
<p>".$value['name']."，您好！</p>
<p>根据公司绩效考核工作安排，请您于".$up_time."登陆考核系统进行打分。</p>
<p>登陆网址为：</p>
<a href='".C("examine_web")."'>".C("examine_web")."</a><br>
<p>您也可以在手机终端进行考核，请扫描二维码：</p>
<img src='cid:a.png' style='border: none;width:200px;height:200px' />
<p>感谢您的支持与配合！</p>";
            }else{
                $new_email_data['email_body'] =  "<p>内容：</p>
<p>".$value['name']."，您好！</p>
<p>根据公司绩效考核工作安排，请您于".$same_time."登陆考核系统进行打分。</p>
<p>登陆网址为：</p>
<a href='".C("examine_web")."'>".C("examine_web")."</a><br>
<p>您也可以在手机终端进行考核，请扫描二维码：</p>
<img src='cid:a.png' style='border: none;width:200px;height:200px' />
<p>感谢您的支持与配合！</p>";
            }

            $email_array[] = $new_email_data;
        }

        $add_result = M("SendEmail")
            ->addAll($email_array);
        if($add_result){
            $this->successReturn("添加发送邮件数据成功");
        }else{
            $this->errorReturn("添加发送邮件数据失败");
        }
    }

    /**
     * 检测批量导入用户文件接口
     */
    public function batchCheckAddUserAction(){
        $file_type = strrchr($_FILES['csv_file']['name'],".");

        if(!$_FILES['csv_file']){
            $this->errorReturn("请上传csv文件");
        }

        $return_message_array = array();
        if($file_type == ".xlsx" || $file_type == ".xls"){
            Vendor('PHPExcel.PHPExcel');
            Vendor('PHPExcel.PHPExcel.IOFactory');
            Vendor('PHPExcel.PHPExcel.Reader.Excel5');
            Vendor('PHPExcel.PHPExcel.Reader.Excel2007');
            //以上三步加载phpExcel的类
            $filename = $_FILES['csv_file']['tmp_name'];

            if ($file_type =='.xlsx') {
                $objReader = new \PHPExcel_Reader_Excel2007();
                $objExcel = $objReader ->load($filename);
            } else if ($file_type =='.xls') {
                $objReader = new \PHPExcel_Reader_Excel5();
                $objExcel = $objReader ->load($filename);
            }
            $sheet = $objExcel ->getSheet(0);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            if($highestRow < 2){
                $this->errorReturn("表格中无数");
            }
            // $highestColumn = $sheet->getHighestColumn(); // 取得总列数

            //循环读取excel表格,读取一条,插入一条
            //j表示从哪一行开始读取  从第二行开始读取，因为第一行是标题不保存
            //$a表示列号

            for($j=2;$j<=$highestRow;$j++) {
                //depart_id,number,username,password,name,phone,email,rank,station,station_type,user_type,add_time
                $row_message = "";

                $depart_name = $objExcel->getActiveSheet()->getCell("A".$j)->getValue();
                $number = $objExcel->getActiveSheet()->getCell("B".$j)->getValue();
                $name = $objExcel->getActiveSheet()->getCell("C".$j)->getValue();
                $username = $objExcel->getActiveSheet()->getCell("D".$j)->getValue();
                $phone = $objExcel->getActiveSheet()->getCell("E".$j)->getValue();
                $email = $objExcel->getActiveSheet()->getCell("F".$j)->getValue();
                $rank = $objExcel->getActiveSheet()->getCell("G".$j)->getValue();
                $station = $objExcel->getActiveSheet()->getCell("H".$j)->getValue();
                $station_type = $objExcel->getActiveSheet()->getCell("I".$j)->getValue();

                if($depart_name){
                    $check_depart_name = M("Department")
                        ->where(['name'=>$depart_name])
                        ->field("depart_id")
                        ->cache(true,60)
                        ->find();
                    if(!$check_depart_name){
                        $row_message = $row_message."部门名称错误，系统中无法匹配到该部门；";
                    }
                }else{
                    $row_message = $row_message."部门名称不能为空；";
                }

                if($number){
                    $check_number = M("User")
                        ->where(['number'=>$number])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_number){
                        $row_message = $row_message."该员工编号已存在，对应员工：".$check_number['name']."；";
                    }
                }

                if(!$name){
                    $row_message = $row_message."姓名不能为空；";
                }

                if(!$username){
                    $row_message = $row_message."账号不能为空；";
                }else{
                    $check_username = M("User")
                        ->where(['username'=>$username])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_username){
                        $row_message = $row_message."该账号已存在，对应员工：".$check_username['name']."；";
                    }
                }

                if($phone){
                    $check_phone = M("User")
                        ->where(['phone'=>$phone])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_phone){
                        $row_message = $row_message."该手机号已存在，对应员工：".$check_phone['name']."；";
                    }
                }

                if($email){
                    $check_email = M("User")
                        ->where(['email'=>$email])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_email){
                        $row_message = $row_message."该邮箱已存在，对应员工：".$check_email['name']."；";
                    }
                }

                if(!$rank){
                    $row_message = $row_message."级别不能为空；";
                }else{
                    if($rank != "员工" && $rank != "部门副职" && $rank != "部门正职" && $rank != "公司高管"){
                        $row_message = $row_message."级别必须填：员工，部门副职，部门正职，公司高管；";
                    }
                    /*if($rank == "员工"){

                    }elseif ($rank == "部门副职"){

                    }elseif ($rank == "部门正职"){

                    }elseif ($rank == "公司高管"){

                    }else{
                        $row_message = $row_message."级别必须填：员工，部门副职，部门正职，公司高管；";
                    }*/
                }

                if($row_message){
                    $return_message_array[] = "第".$j."行：".$row_message;
                }
            }
        }else if($file_type == ".csv"){
            //打开文件
            $file = fopen($_FILES['csv_file']['tmp_name'],"r");
            //读取第一行数据
            $line = fgetcsv($file);
            //判断第一行是否为10列
            //addFileLog("列数：".json_encode($line));
            if(count($line) != 9){
                fclose($file);
                $this->errorReturn("文件格式错误：导入文件列数必须为9列");
            }
            //判断第一列标题是否为工号
            if(iconv('gb2312','utf-8',$line[0]) != "部门"){
                fclose($file);
                $this->errorReturn("文件格式错误：文件第一列标题必须为“部门”");
            }

            $j = 2;
            while($line = fgetcsv($file)){
                $row_message = "";

                $depart_name = iconv('gb2312','utf-8',$line[0]);
                $number = iconv('gb2312','utf-8',$line[1]);
                $name = iconv('gb2312','utf-8',$line[2]);
                $username = iconv('gb2312','utf-8',$line[3]);
                $phone = iconv('gb2312','utf-8',$line[4]);
                $email = iconv('gb2312','utf-8',$line[5]);
                $rank = iconv('gb2312','utf-8',$line[6]);
                $station = iconv('gb2312','utf-8',$line[7]);
                $station_type = iconv('gb2312','utf-8',$line[8]);

                if($depart_name){
                    $check_depart_name = M("Department")
                        ->where(['name'=>$depart_name])
                        ->field("depart_id")
                        ->cache(true,60)
                        ->find();
                    if(!$check_depart_name){
                        $row_message = $row_message."部门名称错误，系统中无法匹配到该部门；";
                    }
                }else{
                    $row_message = $row_message."部门名称不能为空；";
                }

                if($number){
                    $check_number = M("User")
                        ->where(['number'=>$number])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_number){
                        $row_message = $row_message."该员工编号已存在，对应员工：".$check_number['name']."；";
                    }
                }

                if(!$name){
                    $row_message = $row_message."姓名不能为空；";
                }

                if(!$username){
                    $row_message = $row_message."账号不能为空；";
                }else{
                    $check_username = M("User")
                        ->where(['username'=>$username])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_username){
                        $row_message = $row_message."该账号已存在，对应员工：".$check_username['name']."；";
                    }
                }

                if($phone){
                    $check_phone = M("User")
                        ->where(['phone'=>$phone])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_phone){
                        $row_message = $row_message."该手机号已存在，对应员工：".$check_phone['name']."；";
                    }
                }

                if($email){
                    $check_email = M("User")
                        ->where(['email'=>$email])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_email){
                        $row_message = $row_message."该邮箱已存在，对应员工：".$check_email['name']."；";
                    }
                }

                if(!$rank){
                    $row_message = $row_message."级别不能为空；";
                }else{
                    if($rank != "员工" && $rank != "部门副职" && $rank != "部门正职" && $rank != "公司高管"){
                        $row_message = $row_message."级别必须填：员工，部门副职，部门正职，公司高管；";
                    }
                }

                if($row_message){
                    $return_message_array[] = "第".$j."行：".$row_message;
                }
                $j++;
            }
            fclose($file);
        }else{
            $this->errorReturn("文件必须为xls，xlsx，csv文件");
        }
        if($return_message_array){
            $this->returnJson(601,"检测完成",$return_message_array);
        }else{
            $this->successReturn("检测完成，数据正确，请提交上传");
        }
    }

    /**
     * 批量导入用户接口
     */
    public function batchAddUserAction(){
        $file_type = strrchr($_FILES['csv_file']['name'],".");

        if(!$_FILES['csv_file']){
            $this->errorReturn("请上传csv文件");
        }

        $return_message_array = array();
        if($file_type == ".xlsx" || $file_type == ".xls"){
            Vendor('PHPExcel.PHPExcel');
            Vendor('PHPExcel.PHPExcel.IOFactory');
            Vendor('PHPExcel.PHPExcel.Reader.Excel5');
            Vendor('PHPExcel.PHPExcel.Reader.Excel2007');
            //以上三步加载phpExcel的类
            $filename = $_FILES['csv_file']['tmp_name'];

            if ($file_type =='.xlsx') {
                $objReader = new \PHPExcel_Reader_Excel2007();
                $objExcel = $objReader ->load($filename);
            } else if ($file_type =='.xls') {
                $objReader = new \PHPExcel_Reader_Excel5();
                $objExcel = $objReader ->load($filename);
            }
            $sheet = $objExcel ->getSheet(0);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            // $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            if($highestRow < 2){
                $this->errorReturn("表格中无数");
            }
            //循环读取excel表格,读取一条,插入一条
            //j表示从哪一行开始读取  从第二行开始读取，因为第一行是标题不保存
            //$a表示列号
            $model = M();
            $model->startTrans();

            for($j=2;$j<=$highestRow;$j++) {

                $depart_name = $objExcel->getActiveSheet()->getCell("A".$j)->getValue();
                $number = $objExcel->getActiveSheet()->getCell("B".$j)->getValue();
                $name = $objExcel->getActiveSheet()->getCell("C".$j)->getValue();
                $username = $objExcel->getActiveSheet()->getCell("D".$j)->getValue();
                $phone = $objExcel->getActiveSheet()->getCell("E".$j)->getValue();
                $email = $objExcel->getActiveSheet()->getCell("F".$j)->getValue();
                $rank = $objExcel->getActiveSheet()->getCell("G".$j)->getValue();
                $station = $objExcel->getActiveSheet()->getCell("H".$j)->getValue();
                $station_type = $objExcel->getActiveSheet()->getCell("I".$j)->getValue();

                if($depart_name){
                    $check_depart_name = M("Department")
                        ->where(['name'=>$depart_name])
                        ->field("depart_id")
                        ->cache(true,60)
                        ->find();
                    if(!$check_depart_name){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：部门名称错误，系统中无法匹配到该部门");
                    }
                }else{
                    $model->rollback();
                    $this->errorReturn("第".$j."行：部门名称不能为空");
                }

                if($number){
                    $check_number = M("User")
                        ->where(['number'=>$number])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_number){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该员工编号已存在，对应员工：".$check_number['name']);
                    }
                }

                if(!$name){
                    $model->rollback();
                    $this->errorReturn("第".$j."行：姓名不能为空");
                }

                if(!$username){
                    $model->rollback();
                    $this->errorReturn("第".$j."行：账号不能为空");
                }else{
                    $check_username = M("User")
                        ->where(['username'=>$username])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_username){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该账号已存在，对应员工：".$check_username['name']);
                    }
                }

                if($phone){
                    $check_phone = M("User")
                        ->where(['phone'=>$phone])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_phone){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该手机号已存在，对应员工：".$check_phone['name']);
                    }
                }

                if($email){
                    $check_email = M("User")
                        ->where(['email'=>$email])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_email){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该邮箱已存在，对应员工：".$check_email['name']);
                    }
                }

                if(!$rank){
                    $model->rollback();
                    $this->errorReturn("第".$j."行：级别不能为空");
                }else{
                    if($rank != "员工" && $rank != "部门副职" && $rank != "部门正职" && $rank != "公司高管"){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：级别必须填：员工，部门副职，部门正职，公司高管");
                    }
                }

                $new_data = array();
                $new_data['depart_id'] = $check_depart_name['depart_id'];
                $new_data['number'] = $number?$number:"";
                $new_data['username'] = $username;
                $new_data['password'] = $phone?md5(substr($phone,5,6)):md5("123456");
                $new_data['name'] = $name?$name:"";
                $new_data['phone'] = $phone?$phone:"";
                $new_data['email'] = $email?$email:"";
                if($rank == "员工"){
                    $new_data['rank'] = 1;
                }elseif ($rank == "部门副职"){
                    $new_data['rank'] = 3;
                }elseif ($rank == "部门正职"){
                    $new_data['rank'] = 4;
                }elseif ($rank == "公司高管"){
                    $new_data['rank'] = 5;
                }
                $new_data['station'] = $station?$station:"";
                $new_data['station_type'] = $station_type?$station_type:"";
                $new_data['user_type'] = 1;
                $new_data['add_time'] = time();

                $add_result = M("User")
                    ->add($new_data);
                if(!$add_result){
                    $model->rollback();
                    $this->errorReturn("添加数据失败，请重新尝试");
                }
            }
        }else if($file_type == ".csv"){
            //打开文件
            $file = fopen($_FILES['csv_file']['tmp_name'],"r");
            //读取第一行数据
            $line = fgetcsv($file);
            //判断第一行是否为10列
            //addFileLog("列数：".json_encode($line));
            if(count($line) != 9){
                fclose($file);
                $this->errorReturn("文件格式错误：导入文件列数必须为9列");
            }
            //判断第一列标题是否为工号
            if(iconv('gb2312','utf-8',$line[0]) != "部门"){
                fclose($file);
                $this->errorReturn("文件格式错误：文件第一列标题必须为“部门”");
            }

            $model = M();
            $model->startTrans();

            $j = 2;
            while($line = fgetcsv($file)){
                $row_message = "";

                $depart_name = iconv('gb2312','utf-8',$line[0]);
                $number = iconv('gb2312','utf-8',$line[1]);
                $name = iconv('gb2312','utf-8',$line[2]);
                $username = iconv('gb2312','utf-8',$line[3]);
                $phone = iconv('gb2312','utf-8',$line[4]);
                $email = iconv('gb2312','utf-8',$line[5]);
                $rank = iconv('gb2312','utf-8',$line[6]);
                $station = iconv('gb2312','utf-8',$line[7]);
                $station_type = iconv('gb2312','utf-8',$line[8]);

                if($depart_name){
                    $check_depart_name = M("Department")
                        ->where(['name'=>$depart_name])
                        ->field("depart_id")
                        ->cache(true,60)
                        ->find();
                    if(!$check_depart_name){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：部门名称错误，系统中无法匹配到该部门");
                    }
                }else{
                    $model->rollback();
                    $this->errorReturn("第".$j."行：部门名称不能为空");
                }

                if($number){
                    $check_number = M("User")
                        ->where(['number'=>$number])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_number){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该员工编号已存在，对应员工：".$check_number['name']);
                    }
                }

                if(!$name){
                    $model->rollback();
                    $this->errorReturn("第".$j."行：姓名不能为空");
                }

                if(!$username){
                    $model->rollback();
                    $this->errorReturn("第".$j."行：账号不能为空");
                }else{
                    $check_username = M("User")
                        ->where(['username'=>$username])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_username){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该账号已存在，对应员工：".$check_username['name']);
                    }
                }

                if($phone){
                    $check_phone = M("User")
                        ->where(['phone'=>$phone])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_phone){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该手机号已存在，对应员工：".$check_phone['name']);
                    }
                }

                if($email){
                    $check_email = M("User")
                        ->where(['email'=>$email])
                        ->field('name')
                        ->cache(true,60)
                        ->find();
                    if($check_email){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：该邮箱已存在，对应员工：".$check_email['name']);
                    }
                }

                if(!$rank){
                    $model->rollback();
                    $this->errorReturn("第".$j."行：级别不能为空");
                }else{
                    if($rank != "员工" && $rank != "部门副职" && $rank != "部门正职" && $rank != "公司高管"){
                        $model->rollback();
                        $this->errorReturn("第".$j."行：级别必须填：员工，部门副职，部门正职，公司高管");
                    }
                }

                $new_data = array();
                $new_data['depart_id'] = $check_depart_name['depart_id'];
                $new_data['number'] = $number?$number:"";
                $new_data['username'] = $username;
                $new_data['password'] = $phone?md5(substr($phone,5,6)):md5("123456");
                $new_data['name'] = $name?$name:"";
                $new_data['phone'] = $phone?$phone:"";
                $new_data['email'] = $email?$email:"";
                if($rank == "员工"){
                    $new_data['rank'] = 1;
                }elseif ($rank == "部门副职"){
                    $new_data['rank'] = 3;
                }elseif ($rank == "部门正职"){
                    $new_data['rank'] = 4;
                }elseif ($rank == "公司高管"){
                    $new_data['rank'] = 5;
                }
                $new_data['station'] = $station?$station:"";
                $new_data['station_type'] = $station_type?$station_type:"";
                $new_data['user_type'] = 1;
                $new_data['add_time'] = time();

                $add_result = M("User")
                    ->add($new_data);
                if(!$add_result){
                    $model->rollback();
                    $this->errorReturn("添加数据失败，请重新尝试");
                }
                $j++;
            }
            fclose($file);
        }else{
            $this->errorReturn("文件必须为xls，xlsx，csv文件");
        }
        $model->commit();
        $this->successReturn("批量生成账号成功");
    }
}